﻿using System;
using System.IO;

namespace FlowSimulate.ZentaoDB {

    public class ZentaoFileUploader(string fileStore) {

        readonly string fileStore = fileStore;
        readonly Random random = new();

        int counter = 0;

        public string Upload(string originalFilePath, DateTime uploadDate) {
            var yearMonth = uploadDate.ToString("yyyyMM");
            var saveName = this.GenerateUniqueName(uploadDate, originalFilePath);
            var pathName = $"/{yearMonth}/{saveName}";
            var path = Path.Combine(fileStore, pathName);
            System.IO.File.Copy(originalFilePath, path);
            return pathName;
        }

        private string GenerateUniqueName(DateTime uploadDate, string originalFilePath) {
            var r = this.random.Next(0, 10000);
            var c = this.counter++;
            this.counter %= 10000;
            var h = originalFilePath.GetHashCode();
            var ext = Path.GetExtension(originalFilePath);
            var fname = $"{uploadDate:yyyyMMdd}{h:0000}{r:0000}{c:0000}.{ext}";
            return fname;
        }
    }
}
